package web.zz.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import web.zz.utils.HttpContextUtil;
import web.zz.utils.IpUtils;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

@Aspect
@Component
@Slf4j
//@Documented//
//@Inherited
//@Target(ElementType.METHOD)
//@Retention(RetentionPolicy.RUNTIME)
public class LogAspect {
    //@annotation(web.zz.aop.LogAnnotation)是切点表达式，表示加了LogAnnotation注解都是切点
    //pt()就是切点表达式分装好了
    @Pointcut("@annotation(web.zz.aop.LogAnnotation)")
    public void pt(){

    }
    //环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //执行时长
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        recordLog(joinPoint,time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint,long time) throws IOException {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
//        Method realMethod = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(),
//                method.getParameterTypes());
//        Annotation an = method.getAnnotation(UserChangeLog.class);

        log.info("===========log start=============");
        log.info("module:{}",logAnnotation.module());
        log.info("operator:{}",logAnnotation.operator());

        //请求方法名
        String classname = joinPoint.getTarget().getClass().getName();
        String methodName = methodSignature.getName();
        log.info("request method:{}",classname + "." + methodName + "()");

        //请求参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        log.info("ip:{}", IpUtils.getIpAddr(request));

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String loginTime = df.format(System.currentTimeMillis());
        System.out.println("loginTime:"+loginTime);
        log.info("excute time:{} ms",time);
        log.info("===========log end ==============");
    }
}
